import { Stage, Utils, Vector3 } from "babylon-lib/index";
import { CreateUINode, UINode } from 'babylon-lib/gui/base/ui-node';
import { CreateUIRectangle } from "babylon-lib/gui/control/ui-rectangle";
import { CreateUIText, IUITextOptions, UIText } from "babylon-lib/gui/control/ui-text";
import { ANCHOR } from "babylon-lib/gui/control/abstract-base";
import { RenderOrder } from "babylon-lib/misc/render-order";
import * as Data from '../data/data';
import { Control } from "@babylonjs/gui/2D/controls/control";
import { SoundManager } from "../stages/default-stage-components/sound-manager";
import { SoldierManager } from "../stages/default-stage-components/soldier-manager";
import { Landscape } from "../stages/default-stage-components/landscape";


class SettlementPanel {

    private static _taskText: UIText;
    private static _taskStar: UIText;
    private static _enemyText: UIText;
    private static _enemyStar: UIText;
    private static _lifeText: UIText;
    private static _lifeStar: UIText;
    private static _windText: UIText;
    private static _windStar: UIText;
    private static _timeText: UIText;
    private static _timeStar: UIText;
    private static _totalText: UIText;
    private static _totalStar: UIText;
    private static _scores: number[] = [];

    public static node: UINode;

    public static initialize(stage: Stage): void {
        this.initializeNode(stage);
        this.bindData(stage);
    }

    private static bindData(stage: Stage): void {
        const _this = SettlementPanel;
        Data.gameOn.onChange((o, n) => {
            _this.node.display = !n;
            if (!n) {
                SoundManager.reset();
                SoundManager.over.play();
                Data.controlPanelDisplay.value = false;
            }
        });
        Data.taskStatus.onChange((o, n) => {
            switch (n) {
                case Data.taskState.interrupt:
                    _this._taskText.text = '任务：中断';
                    _this._taskStar.text = '⭐';
                    _this._scores[0] = 0.2;
                    break;
                case Data.taskState.failed:
                    _this._taskText.text = '任务：失败';
                    _this._taskStar.text = '⭐⭐⭐';
                    _this._scores[0] = 0.6;
                    break;
                case Data.taskState.success:
                    _this._taskText.text = '任务：完成';
                    _this._taskStar.text = '⭐⭐⭐⭐⭐';
                    _this._scores[0] = 1;
                    break;
            }

            _this.updateScore();
        });
        Data.invalidEnemyNumber.onChange((o, n) => {
            _this._enemyText.text = '歼敌：' + n + '/' + SoldierManager.count;
            const res = _this.calculateStar(n, 0, SoldierManager.count);
            _this._enemyStar.text = res[1];
            _this._scores[1] = res[0];
            _this.updateScore();
        });
        Data.lifeNumber.onChange((o, n) => {
            _this._lifeText.text = '架次：' + n;
            const res = _this.calculateStar(n, SoldierManager.count * 2, SoldierManager.count * 0.5);
            _this._lifeStar.text = res[1];
            _this._scores[2] = res[0];
            _this.updateScore();
        });
        Data.windStrength.onChange((o, n) => {
            _this._windText.text = '天气：' + Utils.normalizeNumber(n,0.001);
            const res = _this.calculateStar(n, 0, Landscape.windRand * 1.415);
            _this._windStar.text = res[1];
            _this._scores[3] = res[0];
            _this.updateScore();
        });
        Data.gameTime.onChange((o, n) => {
            _this._timeText.text = '耗时：' + n;
            const res = _this.calculateStar(n, Landscape.maxTime, 0);
            _this._timeStar.text = res[1];
            _this._scores[4] = res[0];
            _this.updateScore();
        });
    }

    private static updateScore(): void {
        const s = this._scores.reduce((pv, cv, idx, ary) => {
            let fs = 0;
            //total:10
            switch (idx) {
                case 0:
                    fs = cv;
                    break;
                case 1:
                    fs = cv * 4;
                    break;
                case 2:
                    fs = cv * 2;
                    break;
                case 3:
                    fs = cv;
                    break;
                case 4:
                    fs = cv * 2;
                    break;
            }
            return pv + fs;
        });
        const sc = this.calculateStar(s, 0, 10);
        this._totalText.text = '总计：' + Utils.normalizeNumber(sc[0] * 100, 1);
        this._totalStar.text = sc[1];
    }

    private static calculateStar(n: number, tf: number, tt: number): [number, string] {
        const r = (n - tf) / (tt - tf);
        const ss = Math.round(r * 5);
        let s = '';
        for (let i = 0; i < ss; i++) {
            s += '⭐';
        }
        return [Math.min(Math.max(r, 0), 1), s];
    }

    private static initializeNode(stage: Stage): void {
        const opsT: IUITextOptions = {
            anchor: ANCHOR.CENTER,
            width: 2.5,
            height: 1,
            fontColor: '#cecece',
            left: -0.2,
            renderingGroupId: RenderOrder.id(Data.orders.ui),
            textVerticalAlignment: Control.VERTICAL_ALIGNMENT_CENTER,
            textHorizontalAlignment: Control.HORIZONTAL_ALIGNMENT_LEFT,
        };
        const opsS: IUITextOptions = {
            ...opsT,
            left: 0.13,
            width: 3.6,
        };
        const top = 0.18;
        const space = -0.072;
        const node = CreateUINode('settlement-panel-node', stage.mainScene,
            {
                anchor: new Vector3(0.5, 0.5, 0),
                lockToCamera: true,
                display: false,
            },
            [
                CreateUIRectangle('settlement-panel-background', stage.mainScene, {
                    anchor: ANCHOR.CENTER,
                    width: 7,
                    height: 5,
                    cornerRadius: 5,
                    renderingGroupId: RenderOrder.id(Data.orders.uiBack),
                    alpha: 0.7,
                }),
                this._taskText = CreateUIText('settlement-panel-title-task', stage.mainScene, {
                    text: '任务：中断',
                    ...opsT,
                    top: top,
                }),
                this._enemyText = CreateUIText('settlement-panel-title-kill', stage.mainScene, {
                    text: '歼敌：0/' + SoldierManager.count,
                    ...opsT,
                    top: top + space,
                }),
                this._lifeText = CreateUIText('settlement-panel-title-number', stage.mainScene, {
                    text: '架次：1',
                    ...opsT,
                    top: top + space * 2,
                }),
                this._timeText = CreateUIText('settlement-panel-title-time', stage.mainScene, {
                    text: '耗时：0',
                    ...opsT,
                    top: top + space * 3,
                }),
                this._windText = CreateUIText('settlement-panel-title-weather', stage.mainScene, {
                    text: '天气：0',
                    ...opsT,
                    top: top + space * 4,
                }),
                this._totalText = CreateUIText('settlement-panel-title-total', stage.mainScene, {
                    text: '总计：0',
                    ...opsT,
                    top: top + space * 5,
                }),
                this._taskStar = CreateUIText('settlement-panel-title-task-star', stage.mainScene, {
                    text: '⭐',
                    ...opsS,
                    top: top,
                }),
                this._enemyStar = CreateUIText('settlement-panel-title-kill-star', stage.mainScene, {
                    text: '⭐',
                    ...opsS,
                    top: top + space,
                }),
                this._lifeStar = CreateUIText('settlement-panel-title-number-star', stage.mainScene, {
                    text: '⭐',
                    ...opsS,
                    top: top + space * 2,
                }),
                this._timeStar = CreateUIText('settlement-panel-title-time-star', stage.mainScene, {
                    text: '⭐',
                    ...opsS,
                    top: top + space * 3,
                }),
                this._windStar = CreateUIText('settlement-panel-title-weather-star', stage.mainScene, {
                    text: '⭐',
                    ...opsS,
                    top: top + space * 4,
                }),
                this._totalStar = CreateUIText('settlement-panel-title-total-star', stage.mainScene, {
                    text: '⭐',
                    ...opsS,
                    top: top + space * 5,
                }),
            ]);
        this.node = node;
    }

}


export { SettlementPanel };